<?
class Sorter
{
	public $items;
	public $current_key;
	public $current_dir;
	public $order;
	
	private $id;
	private $skip_dir = false;
	private $default_key;
	private $default_dir;
	
	
	public function __construct( $id='sort', $skip_dir = false ) 
	{
		$this->id = $id;
		$this->skip_dir = $skip_dir;
	}
	
	
  function invert()
  {
    if(strpos($this->order,' desc')>0)
    {
      $this->order = str_replace(' desc',' asc',$this->order);
      return;
    }
    if(strpos($this->order,' asc')>0)
    {
      $this->order = str_replace(' asc',' desc',$this->order);
      return;
    }
    $this->order.=' desc';
  }
  
	
	function add($key,$title,$sqlkey='',$dir='asc',$one_way=false)
	{
		if(!$sqlkey) $sqlkey=$key;
		if($this->skip_dir)
		{
			$url_up = queryBuilder($this->id.'_by='.$key.'&'.$this->id.'_dir=&page=');
			$url_down = queryBuilder($this->id.'_by='.$key.'&'.$this->id.'_dir=&page=');
		}
		else
		{
			$url_up = queryBuilder($this->id.'_by='.$key.'&'.$this->id.'_dir=asc&page=');
			$url_down = queryBuilder($this->id.'_by='.$key.'&'.$this->id.'_dir=desc&page=');
		}
		$this->items[] = Array('key'=>$key,
		                       'sqlkey'=>$sqlkey,
							   'dir'=>$dir,
							   'title'=>$title,
							   'url_up'=>$url_up,
							   'url_down'=>$url_down,
								 'one_way'=>$one_way
							   );
		
		// присваиваем самый первый добавленный ключ как дефолтовый с возможностью потом переопределить
		if(!$this->default_key)
		{
			$this->default_key = $key;
			$this->default_dir = $dir;
		}
	}
	
	
	function process()
	{
		if( isset($_GET[$this->id.'_by']) && $_GET[$this->id.'_by'])
    {
      foreach($this->items as $item)
      {
			  if($item['key']==$_GET[$this->id.'_by']) $this->current_key = $item['key'];
      }
    }
		
    if(!$this->current_key)
    {
			$this->current_key = $this->default_key;
    }
		
		$item = $this->findByKey($this->current_key);
		
		if( isset($_GET[$this->id.'_dir']) && $_GET[$this->id.'_dir'])
			$this->current_dir = $_GET[$this->id.'_dir'];
		elseif($item)
			$this->current_dir = $item['dir'];
		else
			$this->current_dir = $this->default_dir;
		
		if($this->current_dir!='asc' && $this->current_dir!='desc') $this->current_dir='asc';
		
		$this->order = $item['sqlkey'];
		if($this->current_dir=='desc')
			$this->order.=' desc';
	}
	
	
	function findByKey($key)
	{
		foreach($this->items as $item)
		{
			if($item['key']==$key) return $item;
		}
	}
	
	
	function setDefault($key,$dir)
	{
		$this->default_key = $key;
		$this->default_dir = $dir;
	}
}

